package org.gcu.filestorage.controller;

import org.gcu.filestorage.api.ErrorCode;
import org.gcu.filestorage.pojo.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/redis/save")
    public RequestResult<String> save(@RequestParam String key,
                                      @RequestParam String value,
                                      @RequestParam long keepSeconds){
        redisTemplate.opsForValue().set(key, value, keepSeconds, TimeUnit.SECONDS);
        RequestResult<String> requestResult = new RequestResult<>();
        requestResult.setResCode(ErrorCode.SUCCESS);
        requestResult.setData(value);
        return requestResult;
    }

    @GetMapping("/redis/get")
    public RequestResult<String> get(String key){
        String value = redisTemplate.opsForValue().get(key);
        RequestResult<String> requestResult = new RequestResult<>();
        requestResult.setResCode(ErrorCode.SUCCESS);
        requestResult.setData(value);
        return requestResult;
    }
}
